﻿using Microsoft.EntityFrameworkCore;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class winForm_AccountManage : Form
    {
        private Account currentAccount;
        private bool resetPasswordFlag = false;


        public winForm_AccountManage()
        {
            InitializeComponent();
        }

        private void textBox_SearchAccount_TextChanged(object sender, EventArgs e)
        {
            UpdateDataGridview();
        }

        private void WinForm_AccountManage_Load(object sender, EventArgs e)
        {
            dataGridView_Accounts.AutoGenerateColumns= false;            //LibraryDbContext.Shared.Accounts.Load();
            dataGridView_Accounts.DataSource = LibraryDbContext.Shared.Accounts.Where(acc => acc.AId!= Global.account.AId).ToList();
            comboBox_AccRole.DataSource = Enum.GetNames(typeof(AccountRole));

            comboBox_Gender.SelectedIndex = 0;
            comboBox_AccRole.SelectedIndex = 0;
        }

        private void button_TempSave_Click(object sender, EventArgs e)
        {
            currentAccount.Role = (AccountRole)comboBox_AccRole.SelectedIndex;
            currentAccount.Gender = comboBox_Gender.Text;
            currentAccount.Name = textBox_Name.Text;
            currentAccount.ID = textBox_ID.Text;
            if (resetPasswordFlag)
                currentAccount.Password = Encryptor.SHA256Encrypt("123456X");
            resetPasswordFlag = false;
            try
            {
                LibraryDbContext.Shared.SaveChanges();
            }
            catch (DbUpdateException ee)
            {
                MessageBox.Show(ee.Message+"\n"+ee.GetType().Name, "保存更改时出错");
            }
            //dataGridView_Accounts.Refresh();
            UpdateDataGridview();
        }

        private void button_ResetPassword_Click(object sender, EventArgs e)
        {
            if (!resetPasswordFlag)
            {
                resetPasswordFlag = true;
                button_ResetPassword.Text = "已重置密码为123456，点击撤销";
            }
            else
            {
                resetPasswordFlag = false;
                button_ResetPassword.Text = "点击重置密码为123456";
            }

        }

        private void dataGridView_Accounts_SelectionChanged(object sender, EventArgs e)
        {
            currentAccount = (Account)dataGridView_Accounts.CurrentRow.DataBoundItem;
            //currentAccount_1 = currentAccount;
            textBox_ID.Text = currentAccount.ID;
            textBox_Name.Text = currentAccount.Name;
            comboBox_Gender.SelectedItem = currentAccount.Gender;
            comboBox_AccRole.SelectedItem = currentAccount.Role.ToString();
        }

        private void button_RemoveAccount_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "确定要删除吗", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                return;

            foreach (DataGridViewRow row in dataGridView_Accounts.SelectedRows) 
            {
                var Books = from b in LibraryDbContext.Shared.Books
                            where b.OwnerID == ((Account)row.DataBoundItem).AId
                            select b;
                foreach (Book b in Books) 
                {
                    b.OwnerID = null;
                }
                LibraryDbContext.Shared.Accounts.Remove((Account)row.DataBoundItem);
            }

            //LibraryDbContext.Shared.Accounts.Remove(currentAccount);
            LibraryDbContext.Shared.SaveChanges();
            UpdateDataGridview();
            //dataGridView_Accounts.Refresh();
        }

        private void UpdateDataGridview()
        {
            if (textBox_SearchAccount.Text == string.Empty)
            {
                dataGridView_Accounts.DataSource = LibraryDbContext.Shared.Accounts.Where(acc => acc.AId!= Global.account.AId).ToList();
            }
            else
            {
                //查询
                this.dataGridView_Accounts.DataSource =
                    (from acc in LibraryDbContext.Shared.Accounts
                     where
                 (
                 (!checkBox_SearchByID.Checked || acc.ID.Contains(textBox_SearchAccount.Text))
                 &&(!checkBox_SearchByName.Checked||acc.Name.ToLower().Contains(textBox_SearchAccount.Text.ToLower()))
                 )
                 ||
                 (
                 (checkBox_SearchByName.Checked&&checkBox_SearchByID.Checked) //两个都没选中
                 ||(acc.ID.Contains(textBox_SearchAccount.Text)||acc.Name.ToLower().Contains(textBox_SearchAccount.Text.ToLower()))
                 )
                 &&
                 acc.AId!= Global.account.AId
                     select acc).ToList();
            }
        }

        private void button_AddAccount_Click(object sender, EventArgs e)
        {
            var __temp = new Account()
            {
                Name = textBox_Name.Text,
                ID = textBox_ID.Text,
                Gender = comboBox_Gender.Text,
                Role = (AccountRole)comboBox_AccRole.SelectedIndex,
                Password = Encryptor.SHA256Encrypt("123456X"),
                RegisterDate = DateTime.Now.Date
            };
            LibraryDbContext.Shared.Accounts.Add(__temp);
            //LibraryDbContext.Shared.SaveChanges();
            //MessageBox.Show($"已成功添加{__temp.Name}的账号{__temp.ID}，初始密码为123456");
            //UpdateDataGridview();
            try
            {
                LibraryDbContext.Shared.SaveChanges();
                MessageBox.Show($"已成功添加{__temp.Name}的账号{__temp.ID}，初始密码为123456");
                UpdateDataGridview();
            }
            catch (DbUpdateException ee)
            {
                MessageBox.Show("增加账户时出错，请检查账号ID是否已经存在或联系管理员\n"+ee.ToString());
            }
        }
    }
}
